library(magrittr)
library(stringr)
library(plyr)
library(tidyverse)
library(broom)


rm(list=ls())
home = 'C:/Users/Jason/Dropbox/VNA_Responsiveness/Analysis/JOP-dataverse/'


assignments = paste0(home, 'individual-level-treatment-assignments.csv') %>%
  read_csv %>%
  mutate(bucket=mapvalues(x=group,
                          from=1:3,
                          to=c('  0% Treated',
                               ' 50% Treated',
                               '100% Treated'))) %>%
  count(province, bucket) %>%
  subset(select=-n)
prov.data = paste0(home, 'provincial-data.csv') %>%
  read_csv %>%
  merge(y=assignments,
        by='province')


covariates = c('fulltime',
               'central_nominated',
               'competitive',
               'local_NA',
               'papi_score',
               'pci_score',
               'delegation',
               'ln_gdpcap_2014',
               'transfers_2016')


prov.diffs = combn(c('  0% Treated',' 50% Treated','100% Treated'), 2) %>%
  adply(2, function(x) {
    t1 = subset(prov.data, bucket==x[1])[,covariates]
    t2 = subset(prov.data, bucket==x[2])[,covariates]
    ldply(colnames(t1), function(y) {
      t.test(unlist(t1[,y]), unlist(t2[,y])) %>% 
        tidy
    }, .inform=T) %>%
      mutate(arm1=x[1], arm2=x[2], 
             variable=colnames(t1),
             arms=str_c(arm1, arm2, sep=' vs. '),
             panel='left')
  }, .inform=T)
prov.diffs$panel[prov.diffs$variable=='transfers_2016'] = 'right'

prov.balance = prov.diffs %>%
  ggplot(aes(x=variable, y=estimate, color=arms,
             ymin=conf.low, ymax=conf.high)) +
  geom_hline(yintercept=0, linetype=3) +
  geom_linerange(size=1, position=position_dodge(width=0.5)) +
  geom_point(size=3, position=position_dodge(width=0.5)) +
  scale_x_discrete(breaks=c('central_nominated','fulltime','local_NA',
                            'competitive','delegation','papi_score',
                            'pci_score','ln_gdpcap_2014'),
                   labels=c('Centrally\nnominated',
                            'Full-time','Local\nassembly\ndelegate',
                            'Competitive\nelection','Delegation\nsize',
                            'PAPI\nscore','PCI\nscore',
                            'Logged\nGDP per\ncapita 2014')) +
  scale_color_brewer(name='Treatment Arm', palette='Set1') +
  facet_wrap(~panel, nrow=1, scales='free') +
  labs(x='Covariate', y='Difference') +
  coord_flip() +
  theme_minimal() +
  theme(panel.border=element_rect(fill=NA, color='black'),
        plot.margin=unit(x=c(0.1, 0.2, 0, 0.1), units='in'),
        legend.position='bottom',
        strip.text=element_blank())
prov.balance

ggsave('appendix-figure-03-1.png', prov.balance, path=home, width=8.5, height=5.5, units='in')
ggsave('appendix-figure-03-1.tiff', prov.balance, path=home, width=8.5, height=5.5, units='in')

